package net.lahuobao.mall.controller.admin;

import net.lahuobao.mall.entity.admin.*;
import net.lahuobao.mall.entity.admin.resultmodel.MallProjectEmployee;
import net.lahuobao.mall.service.admin.MallProjectServiceI;
import net.lahuobao.mall.service.admin.MallShopCardUseServiceI;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Lenovo on 2017/3/22.
 */
@Controller
@RequestMapping("/mallProjectController")
public class MallProjectController extends BaseController {
    @Autowired
    private MallProjectServiceI mallProjectService;
    @Autowired
    private MallShopCardUseServiceI mallShopCardUseService;

    @Autowired
    private CommonService commonService;

    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/projectManager");
        Map map = new HashMap();
        //添加账号查询条件
        String userName = ResourceUtil.getSessionUserName().getUserName();

        map.put("userName", userName);
        DataGrid projects = mallProjectService.getTransProjectALL(map);
        //获取用户权限码 0超级管理员1管理员2项目成员3普通用户
        MallCardRole userRole = mallProjectService.getUserCardRole(ResourceUtil.getSessionUserName().getId());
        if(userRole==null){
            mv.addObject("role",3);
        }else{
            if(userRole.getCode()==0){
                mv.addObject("selectList",projects.getResults());
            }else{
                List resultList = getProjectListByRole(ResourceUtil.getSessionUserName().getId(), projects.getResults());
                mv.addObject("selectList",resultList);
            }
            mv.addObject("role",userRole.getCode());
        }
        return mv;
    }
    private List<MallTransProject> getProjectListByRole(String userId,List<MallTransProject> prjList){
        List<MallTransProjectEmployee> roleList = mallProjectService.getAccountAdminEmployees(userId);
        List<MallTransProject> resList = new ArrayList<MallTransProject>();
        Set<Integer> roleSet = new HashSet<Integer>();
        if(roleList!=null && roleList.size()>0){
            for(MallTransProjectEmployee role :roleList){
                roleSet.add(role.getProjectid());
            }
            if(roleSet!=null && roleSet.size()>0 && prjList!=null && prjList.size()>0){
                for(MallTransProject prj : prjList){
                    if(roleSet.contains(prj.getId())){
                        resList.add(prj);
                    }
                }
            }
        }
        return resList;
    }

    @RequestMapping(params = "projects")
    public ModelAndView projects(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/projectChoseList");
        return mv;
    }

    @RequestMapping(params = "projectChooseList")
    public void projectChooseList(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map<String, Object> map = getPageQueryMap(request, dataGrid);
        DataGrid projects = mallProjectService.getTransProjectALL(map);
        projects.setField(dataGrid.getField());
        TagUtil.datagrid(response, projects);
    }

    @RequestMapping(params = "projectList")
    @ResponseBody
    public BootstrapPageResult getAllProjectInfo(HttpServletRequest req){
        BootstrapPageResult j = new BootstrapPageResult();
        j.setSuccess(true);
        try {
            Map<String,Object> map = getRequestParam(req);
            //添加账号查询条件
            String userName = ResourceUtil.getSessionUserName().getUserName();
            map.put("userName", userName);
            DataGrid projects = mallProjectService.getTransProjectALL(map);
            //获取用户权限码 0超级管理员1管理员2项目成员3普通用户
            MallCardRole userRole = mallProjectService.getUserCardRole(ResourceUtil.getSessionUserName().getId());
            if(userRole!=null && userRole.getCode()==0){
                List<MallTransProject> prjList = projects.getResults();
                if(prjList!=null && prjList.size()>0){
                    for(MallTransProject prj : prjList){
                        prj.setIsAdmin(true);
                        prj.setIsMine(true);
                    }
                }
            }else{
                List<MallTransProject> prjList = projects.getResults();
                if(prjList!=null && prjList.size()>0){
                    for(MallTransProject prj : prjList){
                        prj.setIsAdmin(false);
                        prj.setIsMine(false);
                    }
                }
            }
            j.setRows(projects.getResults());
            j.setTotal(projects.getTotal());
        } catch (Exception e) {
            j.setSuccess(false);
        }
        return j;
    }

    @RequestMapping(params = "projectEmpList")
    @ResponseBody
    public BootstrapPageResult getProjectEmployeeInfo(HttpServletRequest req){
        BootstrapPageResult j = new BootstrapPageResult();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            map.put("userId",ResourceUtil.getSessionUserName().getId());
            DataGrid projects = mallProjectService.getProjectEmployee(map);
            j.setRows(projects.getResults());
            j.setTotal(projects.getTotal());
        } catch (Exception e) {
            j.setSuccess(false);
        }
        return j;
    }

    @RequestMapping(params = "addProjectEmp")
    @ResponseBody
    public AjaxJson addProjectEmployeeInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.addProjectEmployee(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "updateProjectEmp")
    @ResponseBody
    public AjaxJson updateProjectEmployeeInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.modifyProjectEmployeeInfo(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "delProjectEmp")
    @ResponseBody
    public AjaxJson delProjectEmployeeInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.delProjectEmployee(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "addProject")
    @ResponseBody
    public AjaxJson addProjectInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.addMallProject(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "updateProject")
    @ResponseBody
    public AjaxJson updateProjectInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.modifyProjectInfo(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "delProject")
    @ResponseBody
    public AjaxJson delProjectInfo(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            mallProjectService.delProject(map);
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "checkProject")
    @ResponseBody
    public AjaxJson checkProject(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            int count = mallProjectService.getProjectCount(map);
            j.setMsg("操作成功");
            j.setObj(count);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "checkProjectEmp")
    @ResponseBody
    public AjaxJson checkProjectEmp(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        try {
            Map map = getRequestParam(req);
            DataGrid prjEmpDataGrid = mallProjectService.getProjectEmployee(map);
            List<MallProjectEmployee> projectEmployeeList = prjEmpDataGrid.getResults();
            if(projectEmployeeList!=null && projectEmployeeList.size()>0){
                j.setObj(projectEmployeeList.size());
            }else{
                j.setObj(0);
            }
            j.setMsg("操作成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(params = "cardInfo")
    public ModelAndView cardInfo(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/cardInfo");
        String cardno = request.getParameter("cardno");
        mv.addObject("cardno",cardno);
        MallShopCardUseEntity cardinfo = mallShopCardUseService.getCardNoInfo(cardno);
        mv.addObject("state",cardinfo.getUseStatus());
        return mv;
    }

    @RequestMapping(params = "cardInfoDatagrid")
    public void cardInfoDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map map = getRequestParam(request);
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        int num = Integer.valueOf(page)-1;
        int row = Integer.valueOf(rows);
        int offset = num*row;
        map.put("offset",offset);
        map.put("limit",row);
        map.put("isPage","true");
        DataGrid dg = mallProjectService.getMallCardInfo(map);
        dataGrid.setTotal(dg.getTotal());
        dataGrid.setResults(dg.getResults());
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 加载全部
     * @param req
     * @return
     */
    @RequestMapping(params = "loadall")
    @ResponseBody
    public AjaxJson loadall(HttpServletRequest req){
        AjaxJson j = new AjaxJson();
        try {
            //判断改用户所属的项目
            HttpSession session = ContextHolderUtils.getSession();
            TSUser user = (TSUser)session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
            //查询该人员未删除的所在项目
            CriteriaQuery projectUserCq = new CriteriaQuery(MallProjectUserBaseEntity.class);
            projectUserCq.eq("accountid", user.getId());
            projectUserCq.eq("isdelete", false);
            projectUserCq.add();
            List<MallProjectUserBaseEntity> lists = commonService.getListByCriteriaQuery(projectUserCq, false);
            //返回项目
            List<MallTransProjectEntity> result = new ArrayList<MallTransProjectEntity>();
            if(lists.size() > 0){
                CriteriaQuery projectCq = new CriteriaQuery(MallTransProjectBaseEntityEntity.class);
                List<Integer> paramLists = new ArrayList<Integer>();
                for(int i = 0; i < lists.size(); i++){
                    //是否为管理员
                    if(lists.get(i).getIsadmin()){
                        paramLists.add(lists.get(i).getProjectid());
                    }
                }
                if(paramLists.size() > 0 ){
                    projectCq.in("id", paramLists.toArray());
                    projectCq.eq("isdelete", false);
                    projectCq.add();
                    result = commonService.getListByCriteriaQuery(projectCq, false);
                }
            }else {
                //admin 所有未删除的项目
                CriteriaQuery projectCq = new CriteriaQuery(MallTransProjectBaseEntityEntity.class);
                projectCq.eq("isdelete", false);
                projectCq.add();
                result = commonService.getListByCriteriaQuery(projectCq, false);
            }
            j.setObj(result);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试！");
        }
        return j;
    }

    /**
     * 根据项目id获取项目人员
     * @param
     * @return
     */
    @RequestMapping(params = "getprojectuser")
    @ResponseBody
    public AjaxJson getProjectUser(String projectId){
        AjaxJson j = new AjaxJson();
        try {
            String sql = " select * from  lahuobao.mall_trans_project_employee where isdelete = 0 and  projectId in (" + projectId +")";
            j.setObj(commonService.findListbySql(sql, MallProjectUserBaseEntity.class));
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试！");
        }
        return j;
    }

}
